package com.colouredglaze.controller;

import com.colouredglaze.entity.TbAddress;
import com.colouredglaze.entity.TbUser;
import com.colouredglaze.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ZhangLin
 * @version 1.0
 * @date 2020/11/27 19:23
 */
@Controller
@RequiredArgsConstructor
@RequestMapping("/Address")
public class AddressController {

    private final AddressService addressService;

    //插入或修改地址
    @RequestMapping(value = "/addupdateAddress", method = RequestMethod.POST)
    public ModelAndView addAddress(Integer rid, String uid, String address, String rname, String rphone) {
        TbAddress tbAddress;
        if (rid == null) {
            tbAddress = TbAddress.QueryBuild().address(address).rname(rname).uid(uid).rphone(rphone);
            Integer i = addressService.insertAddress(tbAddress);
        } else {
            tbAddress = TbAddress.QueryBuild().rid(rid).address(address).rname(rname).uid(uid).rphone(rphone);
            Integer integer = addressService.updateAddress(tbAddress);
        }
        return new ModelAndView("redirect:/Address/allAddress", "uid", uid);
    }

    //查询所有地址
    @RequestMapping("/allAddress")
    public ModelAndView selectAllAddress(HttpServletRequest request) {
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        String uid = user.getUid();
        List<TbAddress> addressList;
        TbAddress address = TbAddress.QueryBuild().uid(uid);
        addressList = addressService.selectAllAddress(address);
        return new ModelAndView("/user/address", "addressList", addressList);
    }

    //删除一条收货地址
    @RequestMapping("/deleteAddress")
    public ModelAndView deleteAddress(Integer rid, HttpServletRequest request) {
        Integer integer = 0;
        integer = addressService.deleteAddress(rid);
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        String uid = user.getUid();
        return new ModelAndView("redirect:/Address/allAddress", "uid", uid);
    }


}
